<?php
/**
 * User: xialei
 * Date: 2016/7/2 0002
 * Time: 15:27
 */

namespace app\modules\admin\controllers;


use app\commands\CommonTool;
use app\models\Prize;
use app\models\Win;
use PHPExcel_IOFactory;
use yii\base\Exception;
use yii\base\UserException;
use yii\db\ActiveQuery;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class PrizeController extends Controller
{
    public function actionAll()
    {
        return Prize::find()->asArray()->all();
    }

    public function actionDelete($id)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //删除奖品，
            $prize = Prize::findOne($id);
            if (empty($prize)) {
                throw new UserException('奖品不存在！');
            }
            if (!$prize->delete()) {
                throw new UserException('奖品删除失败');
            }
            //删除中奖
            $result = Win::deleteAll(['prizeId' => $id]);
            if ($result === false) {
                throw new UserException('删除中奖失败');
            }
//            $transaction->commit();
            return ['errmsg' => '删除成功', 'errcode' => 0];
        } catch (Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 添加|编辑
     * @param int $id
     * @return Prize
     * @throws NotFoundHttpException
     * @throws UserException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionPost($id = 0)
    {
        if ($id > 0) {
            /** @var Prize $prize */
            $prize = Prize::findOne($id);
            if (empty($prize)) {
                throw new NotFoundHttpException('奖品不存在');
            }
        } else {
            $prize = new Prize();
        }
        $prize->setAttributes(\Yii::$app->request->getBodyParams());
        if (!$prize->save()) {
            throw new UserException(CommonTool::getFirstError($prize));
        }
        return $prize;
    }

    /**
     * 中奖列表
     * @param int $max
     * @param int $size
     * @param string $keyword
     * @return array
     */
    public function actionWins($max = 0, $size = 30, $keyword = '')
    {
        $query = Win::find()->limit($size)->orderBy(['{{%win}}.createdAt' => SORT_DESC]);
        if ($max > 0) {
            $query->andWhere(['<', '{{%win}}.createdAt', $max]);
        }
        $query->innerJoinWith(['user' => function (ActiveQuery $q) use ($keyword) {
            if (!empty($keyword)) {
                $q->andWhere([
                    'OR',
                    ['like', 'nickname', $keyword],
                    ['like', 'realname', $keyword],
                    ['like', 'phone', $keyword]
                ]);
            }
        }, 'prize']);
        $count = $query->count();
        $list = $query->asArray()->all();
        return [
            'list' => $list,
            'count' => $count
        ];
    }

    /**
     * 兑奖
     * @param int $code
     * @param int $exchange
     * @return Win
     * @throws NotFoundHttpException
     * @throws UserException
     */
    public function actionExchange($code = 0, $exchange = 1)
    {
        /** @var Win $win */
        $win = Win::findOne($code);
        if (empty($win)) {
            throw new NotFoundHttpException('中奖纪录不存在');
        }
        $win->isExchange = $exchange;
        if (!$win->save()) {
            throw new UserException('操作失败');
        }
        return $win;
    }

    /**
     * 奖品
     * @param $id
     * @return null|static
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        $data = Prize::findOne($id);
        if (empty($data)) {
            throw new NotFoundHttpException('奖品不存在');
        }
        return $data;
    }

    public function actionExport()
    {
        //导出中奖
        \Yii::$app->response->format = Response::FORMAT_RAW;
        $query = Win::find()->innerJoinWith(['user', 'prize']);
        $phpexcel = new \PHPExcel();
        $phpexcel->setActiveSheetIndex(0);
        $phpexcel->getActiveSheet()
            ->setCellValue('A1', 'openid')
            ->setCellValue('B1', '昵称')
            ->setCellValue('C1', '姓名')
            ->setCellValue('D1', '电话')
            ->setCellValue('E1', '奖品名称')
            ->setCellValue('F1', '验证码')
            ->setCellValue('G1', '银行')
            ->setCellValue('H1', '身份证正面')
            ->setCellValue('I1', '身份证反面')
            ->setCellValue('J1', '银行卡反面')
            ->setCellValue('K1', '注册时间')
            ->setCellValue('L1', '中奖时间')
            ->setCellValue('M1', '已领奖');
        $i = 1;
        /**
         * @var $row Win
         */
        foreach ($query->each() as $row) {
            $i++;
            $phpexcel->getActiveSheet()
                ->setCellValue('A' . $i, $row->openid)
                ->setCellValue('B' . $i, $row->user->nickname)
                ->setCellValue('C' . $i, $row->user->realname)
                ->setCellValue('D' . $i, $row->user->phone)
                ->setCellValue('E' . $i, $row->prize->title)
                ->setCellValue('F' . $i, $row->code)
                ->setCellValue('G' . $i, $row->user->bank)
                ->setCellValue('H' . $i, $row->user->img1)
                ->setCellValue('I' . $i, $row->user->img2)
                ->setCellValue('J' . $i, $row->user->img3)
                ->setCellValue('K' . $i, date('m-d H:i', $row->user->createdAt))
                ->setCellValue('L' . $i, date('m-d H:i', $row->createdAt))
                ->setCellValue('M' . $i, $row->isExchange ? '√' : '×');
        }
        $phpexcel->getActiveSheet()->setTitle('User');
        $phpexcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . urlencode('导出') . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel2007');
        $objWriter->save('php://output');
        \Yii::$app->end();
    }
}